var app = getApp();
const {
  $Toast
} = require('../../dist/base/index');
var server = require('../../utils/server');
Page({
  data: {
    shopInfo: {},
    goods: {},
    goPage:'NoPay',
    cur_classifyId: "",
    goodsList: [{
      shopClassifyId: '',
      catName: '全部',
   }],
    cart: {
      count: 0,
      total: 0,
      list: {}
    },
    showCartDetail: false
  },
  onLoad: function(options) {
    let that = this;
    that.getAddrs()
    that.setData({
      imgUrl: wx.getStorageSync('imgUrl'),
      lng: options.lng,
      lat: options.lat
    })
    var shopId = options.id;
    wx.setStorageSync("shopId", shopId);
    let curClassifyid = this.data.cur_classifyId;
    this.shopStore(shopId, curClassifyid);
    this.getClassify(shopId);
    // for (var i = 0; i < app.globalData.shops.length; ++i) {
    // 	if (app.globalData.shops[i].id == shopId) {
    // 		this.setData({
    // 			shop: app.globalData.shops[i]
    // 		});
    // 		break;
    // 	}
    // }
  },

  onShow: function() {
    this.setData({
      classifySeleted: ""
    });
  },
  onUnload:function(e){
   if(this.data.goPage!='pay'){
     this.clearCart();
     console.log("删除成功")
   }
   
  },
  openLoc() {
    wx.openLocation({
      latitude: Number(this.data.lat),
      longitude: Number(this.data.lng),
      scale: 15,
      address: this.data.info.shopSite
    })
  },
  buyCartAdd(id) {
    let _that = this;
    let uid = wx.getStorageSync('uid');
    let shopId = wx.getStorageSync('shopId');
    server.postReq('/mobile/shoppingTrolley/addShoppingTrolley', {
      userId: uid,
      shopId: shopId,
      goodsId: id
    }, function(res) {
      if (res.data.code == 1) {
        _that.handleText('加入成功')
      }
    })
  },
  buyCartReduce(id) {
    let _that = this;
    let uid = wx.getStorageSync('uid');
    let shopId = wx.getStorageSync('shopId');
    server.postReq('/mobile/shoppingTrolley/deleteShoppingTrolley', {
      userId: uid,
      shopId: shopId,
      goodsId: id
    }, function(res) {
      if (res.data.code == 1) {
        _that.handleText('移除成功')
      }
    })
  },
  disc(arr) {
    var flag = "";
    if (Object.prototype.toString.call(arr).split(' ')[1].split(']')[0] != 'Array') {
      flag = "无满减活动";
    } else {
      var flag = "";
      for (var i = 0; i < arr.length; i++) {

        let item = "满" + arr[i].meet + "减" + arr[i].minus + ",";
        flag += item;
      }




    }
    return flag;
  },
  tapAddCart: function(e) {

    this.setData({
      curPrice: e.target.dataset.price
    })

    this.addCart(e.target.dataset.id);
    this.buyCartAdd(e.target.dataset.id);
    var goods = this.data.goods;
    let val = goods[e.target.dataset.id].chooseNum + 1;

    goods[e.target.dataset.id].chooseNum = val;
    var newgoods = goods;
    this.setData({
      goods: newgoods,
      curPrice: e.target.dataset.price
    })

  },
  tapReduceCart: function(e) {
    this.setData({
      curPrice: e.target.dataset.price
    })
    this.reduceCart(e.target.dataset.id);
    this.buyCartReduce(e.target.dataset.id);

    var goods = this.data.goods;

    let val = goods[e.target.dataset.id].chooseNum - 1;
    if (val > -1) {
      goods[e.target.dataset.id].chooseNum = val;
      var newgoods = goods;
      this.setData({
        goods: newgoods,

      })
    }

  },
  addCart: function(id) {
    var num = this.data.cart.list[id] || 0;
    this.data.cart.list[id] = num + 1;
    this.countCart();
  },
  reduceCart: function(id) {
    var num = this.data.cart.list[id] || 0;
    if (num <= 1) {
      delete this.data.cart.list[id];
    } else {
      this.data.cart.list[id] = num - 1;
    }
    this.countCart();
  },
  countCart: function() {

    var count = 0,
      total = 0;
    var allGoods = this.data.allGoods;
    for (var id in this.data.cart.list) {

      var goods = this.data.goods[id];
      count += this.data.cart.list[id];
      total += allGoods[id].price * this.data.cart.list[id];
    }

    this.data.cart.count = count;
    this.data.cart.total = total;

    this.setData({
      cart: this.data.cart
    });
  },
  follow: function() {
    this.setData({
      followed: !this.data.followed
    });
  },
  onGoodsScroll: function(e) {
    if (e.detail.scrollTop > 10 && !this.data.scrollDown) {
      this.setData({
        scrollDown: true
      });
    } else if (e.detail.scrollTop < 10 && this.data.scrollDown) {
      this.setData({
        scrollDown: false
      });
    }

    var scale = e.detail.scrollWidth / 570,
      scrollTop = e.detail.scrollTop / scale,
      h = 0,
      classifySeleted,
      len = this.data.goodsList.length;
    this.data.goodsList.forEach(function(classify, i) {
      var _h = 70 + classify.goods.length * (46 * 3 + 20 * 2);
      if (scrollTop >= h - 100 / scale) {
        classifySeleted = classify.id;
      }
      h += _h;
    });
    this.setData({
      classifySeleted: classifySeleted
    });
  },
  tapClassify: function(e) {
    var id = e.target.dataset.id;
    var shopId = wx.getStorageSync('shopId');

    this.shopStore(shopId, id)
    // this.setData({
    // 	classifyViewed: id
    // });
    var self = this;
    setTimeout(function() {
      self.setData({
        classifySeleted: id
      });
    }, 100);
  },
  showCartDetail: function() {
    this.setData({
      showCartDetail: !this.data.showCartDetail
    });
  },
  hideCartDetail: function() {
    this.setData({
      showCartDetail: false
    });
  },
  //预支付订单
  beforeOrder(JSONstr) {
    var that = this;
    let list = that.data.cart.list;
    let uid = wx.getStorageSync('uid');
    let shopId = wx.getStorageSync('shopId');
    server.postReq("/mobile/shoppingTrolley/produceOrderForm", {
      userId: uid,
      shopId: shopId,
      ids: JSONstr,
    }, function(res) {

      if (res.data.code == 1) {
        console.log('---------预支付订单--------');

        wx.redirectTo({
          url: '../payOrder/payOrder?orderData=' + JSON.stringify(res.data.data),
        })
      }
    })
  },

  submit: function(e) {
    if (this.data.cart.count == 0) {
      this.handleText("你还没选商品");
      return false;
    }

    var _that = this;
    _that.setData({
      goPage:'pay'
    })
    var Js = new Array();
    var list = _that.data.cart.list;

    for (let i in list) {
      var newobj = new Object();
      newobj.id = i;
      newobj.num = list[i];
      Js.push(newobj);
    }

    var str = JSON.stringify(Js);
    wx.setStorageSync('ids', str);
    _that.beforeOrder(str)


  },
  getClassify(shopId) {
    let self = this;
    // let uid = wx.getStorageSync('uid');
    server.postReq('/mobile/goods/selectShopClassify', {
      shopId: shopId,
    }, function(res) {
      if (res.data.code == 1) {
        var info = res.data.data;
        console.log(info)
        var goodList = self.data.goodsList;

        var newArr = goodList.concat(info);
        self.setData({
          goodsList: newArr
        })
      }
    })
  },
  shopStore(shopId, classifyId) {
    //商铺信息
    let self = this;
    let uid = wx.getStorageSync('uid');
    server.postReq("/mobile/goods/goodsList", {
      userId: uid,
      shopClassifyId: classifyId,
      shopId: shopId
    }, function(res) {
      if (res.data.code == 1) {

        var info = res.data.data;
        var data = info.goods;
        let newgood = new Object();
        let idArr = new Array();
        var list = self.data.cart.list;
        
        for (let [index, item] of data.entries()) {
          let id = item.id;
          newgood[id] = item;
          newgood[id].chooseNum = 0;
          for (let j in list) {
              if(id==j){
               newgood[id].chooseNum=list[j];
             }  
          }
         
          idArr.push(id);
        }
        var list = self.data.goodsList;
        list[0].goods = idArr;
        info.mm = self.disc(info.meetMInus);
        if (classifyId == '') {
          self.setData({
            allGoods: newgood,
          })
        } else {

        }
        self.setData({
          goods: newgood,

          goodsList: list,
          info: info
        })
      }
    })
  },
  getAddrs() {
    let that = this;
    let uid = wx.getStorageSync('uid');
    server.postReq("/mobile/PersonalCenter/lookReceiverAddress", {
      userId: uid
    }, function(res) {
      if (res.data.code == 1) {

        if (res.data.data.length) {

        } else {
          // that.setAddr()
          that.handleText('请先设置收货地址');
          setTimeout(function() {
            wx.navigateTo({
              url: '../address/address',
            })
          }, 1500);
        }

      }
    })
  },
  clearCart() {
    let uid = wx.getStorageSync('uid');
    let shopId = wx.getStorageSync('shopId');
    let that = this;
    server.postReq('/mobile/shoppingTrolley/deleteShopShoppingTrolley', {
      userId: uid,
      shopId: shopId
    }, function (res) {
      if (res.data.code == 1) {

      }
    })
  },
  setAddr() {
    let that = this;
    var obj = new Object();
    obj.userId = wx.getStorageSync('uid');
    obj.name = "收货人";
    obj.site = "设置收货地址";
    obj.phone = "00000000000";
    obj.isDefault = 1;
    obj.longitude = "112.45361";
    obj.latitude = "34.61812";
    server.postReq("/mobile/PersonalCenter/addReceiverAddress", obj, function(res) {
      if (res.data.code == 1) {

      }
    })
  },
  handleText(msg) {
    $Toast({
      content: msg
    });
  },
});